package com.boot.controller;

import com.boot.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Controller
public class MyController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/index")
    public String index(){
        Subject subject = SecurityUtils.getSubject();
        log.info("subject->"+subject);
        return "index";
    }

    @GetMapping("/administrator")
    public String administrator(){
        return "administrator";
    }

    @GetMapping("/main")
    public String main(){
        return "main";
    }

    @GetMapping("/manage")
    public String manage(){
        return "manage";
    }

    /*
     * @功能描述 使用Shiro认证
     **/
    @RequestMapping("/login")
    public String login(String username,String password,boolean rememberMe, Model model) {

        //1、获取subject
        Subject subject = SecurityUtils.getSubject();

        //2、封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,rememberMe);

        //3、执行登录方法
        try {
            //交给Realm处理--->执行它的认证方法
            subject.login(token);
            //登录成功
            return "redirect:/index";
        }catch (UnknownAccountException e){
            //登录失败:用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            //登录失败：密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }


    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @RequestMapping("/unauth")
    @ResponseBody
    public String unauth(){
        return "未授权没有访问权限";
    }
}
